import os
from PIL import Image

def compress_image(image_path, max_size=(4096, 4096), max_quality=85):
    image = Image.open(image_path)
    image.thumbnail(max_size, Image.LANCZOS)
    q = 85 - (100 * os.path.getsize(image_path) / (max_size[0] * max_size[1] * max_quality))
    if q < 0:
        q = 0
    image.save(image_path, quality=int(q))

def compress_images_in_folder(folder_path, max_folder_size=4 * 1024 * 1024):
    compressed_images = 0
    removed_images = 0
    for root, dirs, files in os.walk(folder_path):
        total_size = 0
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                file_path = os.path.join(root, file)
                file_size = os.path.getsize(file_path)
                total_size += file_size
                if total_size > max_folder_size:
                    if file_size > (max_folder_size - (total_size - file_size)):
                        compress_image(file_path)
                        compressed_images += 1
                        print(f"Compressed {file_path} to fit under {max_folder_size} bytes.")
                    else:
                        os.remove(file_path)
                        removed_images += 1
                        print(f"Removed {file_path} because it would exceed {max_folder_size} bytes after compression.")
                elif file_size > max_folder_size:
                    os.remove(file_path)
                    removed_images += 1
                    print(f"Removed {file_path} because its size is greater than {max_folder_size}.")

    print(f"Compressed {compressed_images} images.")
    print(f"Removed {removed_images} images.")

# folder_path = r"G:\湘潭县属性数据库检查\pic\河口"
folder_path = "pic"
compress_images_in_folder(folder_path)
